package com.vancouver.knows.ui.base;

import java.lang.ref.WeakReference;

import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;

import com.pangu.AMHandler;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.business.BusinessModule;

/**
 * 基础fragment Created by chenxunlin01 on 2015/11/5.
 */
public abstract class BaseFragment extends Fragment {

	// 处理器
	private MMHandler mmHandler;
	protected MainApplication imContext;
	protected BusinessModule bModule;

	@Nullable
	@Override
	final public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		imContext = (MainApplication) getActivity().getApplication();
		bModule = imContext.getBusinessModule();
		// 注册处理器
		mmHandler = new MMHandler(this);
		MainApplication.getInstance().registerSubHandler(mmHandler);
		View rootView = createView(inflater, container, savedInstanceState);
		ButterKnife.bind(this, rootView);
		bindView(rootView);

		return rootView;
	}

	protected abstract View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

	protected abstract void bindView(View rootView);

	@Override
	public void onDestroyView() {
		// 取消注册其处理
		if (mmHandler != null) {
			MainApplication.getInstance().unregisterSubHandler(mmHandler);
		}
		super.onDestroyView();
	}

	public void subHandleMessage(Message msg) {

	}

	/**
	 * 主界面消息处理器，希望它存在的时候处理所有可能的消息
	 */
	private static class MMHandler extends AMHandler {

		private final WeakReference<BaseFragment> mFragmentRef;

		public MMHandler(BaseFragment fragment) {
			super();

			mFragmentRef = new WeakReference<BaseFragment>(fragment);
		}

		@Override
		public void handleMessage(Message msg) {
			BaseFragment fragment = mFragmentRef.get();
			if (fragment == null) {
				return;
			}

			// 如果已经调用了finish了。则不处理
			if (fragment.isRemoving()) {
				return;
			}
			switch (msg.what) {
			default:
				fragment.subHandleMessage(msg);
				break;
			}
		}
	}
}
